﻿using System;
using System.Configuration;
using System.Web.Http.Controllers;
using ESoft.Core.Jwt.Model;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;

namespace ESoft.Core.Jwt
{
    public class JwtUtils
    {
        private static string secret = ConfigurationManager.AppSettings["SecureKey"];

        public static String SaveToken(AuthInfo authInfo)
        {
            try
            {
                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow();

                var unixEpoch = JwtValidator.UnixEpoch; // 1970-01-01 00:00:00 UTC
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                authInfo.Exp = secondsSinceEpoch;

                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                return encoder.Encode(authInfo, secret);
            }
            catch
            {
                throw new Exception("生成token失败！");
            }
        }

        public static AuthInfo DecodeToken(string token)
        {
            IJsonSerializer serializer = new JsonNetSerializer();

            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
            AuthInfo authInfo = decoder.DecodeToObject<AuthInfo>(token, secret, verify: true);

            return authInfo;
        }

        public static AuthInfo GetAuthInfoFromContext(HttpRequestContext requestContext)
        {
            return requestContext.RouteData.Values["auth"] as AuthInfo;
        }
    }
}
